//
//  HttpNewBaseService.m
//  huitravel
//
//  Created by umios on 12-11-12.
//  Copyright (c) 2012年 umios. All rights reserved.
//
#import "HttpNewBaseService.h"
#import "MTJson.h"
#import <CommonCrypto/CommonDigest.h>
#import <AssetsLibrary/AssetsLibrary.h>


@implementation HttpNewBaseService

+ (instancetype)sharedClient {
    static HttpNewBaseService *_sharedClient = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[HttpNewBaseService alloc] initWithBaseURL:[NSURL URLWithString:SERVER_IP]];
        _sharedClient.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
        _sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", @"text/plain", nil];

        _sharedClient.isHidenLoadingView = NO;
        
    });
    
    return _sharedClient;
}
/*************************************************
 Description:POST方法
 **************************************************/
-(void) postFileRequestOperation:(NSString *) operationPath
                 paramDictionary:(NSMutableDictionary *)paramDic
       constructingBodyWithBlock:(CommonfileFormDataBlock) fileFormDataBlock
                    onCompletion:(CommonStringResponseBlock) completion
                         onError:(CommonErrorBlock) errorBlock
                      onAnimated:(BOOL)animated{
    _isHidenLoadingView = animated;
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [self paramMd5WithSign:paramDic];
    
    
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self POST:operationPath parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        fileFormDataBlock(formData);
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        NSLog(@"%s",object_getClassName(responseObject));
        if( [responseObject isKindOfClass:[NSDictionary class]])
        {
            if((!responseObject || responseObject == nil) )
            {
                [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                return ;
            }
            
        }
        
        completion([responseObject JSONString]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        if (error.code) {
            NSLog(@"%@", [error debugDescription]);
            [self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
            return;
        }
        errorBlock(error);
    }];
    
    
}

/*************************************************
 Description:POST方法
 **************************************************/
-(void) postRequestOperation:(NSString *) operationPath
                            paramDictionary:(NSMutableDictionary *)paramDic
                               onCompletion:(CommonStringResponseBlock) completion
                                    onError:(CommonErrorBlock) errorBlock
                                 onAnimated:(BOOL)animated{
    _isHidenLoadingView = animated;
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [self paramMd5WithSign:paramDic];
    

    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];

    [self POST:operationPath parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        NSLog(@"%s",object_getClassName(responseObject));
        if( [responseObject isKindOfClass:[NSDictionary class]])
        {
            if((!responseObject || responseObject == nil) )
            {
                [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                return ;
            }
            
        }
        
        completion([responseObject JSONString]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        if (error.code) {
            NSLog(@"%@", [error debugDescription]);
            [self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
            return;
        }
        errorBlock(error);
    }];
    
}
/*************************************************
 Description:GET方法
 **************************************************/
-(void) getRequestOperation:(NSString *) operationPath
                            paramDictionary:(NSMutableDictionary *)paramDic
                               onCompletion:(CommonStringResponseBlock) completion
                                    onError:(CommonErrorBlock) errorBlock
                                 onAnimated:(BOOL)animated{
    _isHidenLoadingView = animated;
    //[[UIApplication sharedApplication].keyWindow viewWithTag:1212].hidden = NO;
    //zsg:注销
    
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    //添加sign参数
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [self paramMd5WithSign:paramDic];
//    HttpNewBaseService* manager = [HttpNewBaseService sharedClient];
//    self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    [self GET:operationPath parameters:paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if( [responseObject isKindOfClass:[NSDictionary class]])
        {
            if((!responseObject || responseObject == nil) )
            {
                [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                return ;
            }
            
        }
        
        completion([responseObject JSONString]);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (error.code) {
            NSLog(@"%@", [error debugDescription]);
            //[self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
            //return;
        }
        errorBlock(error);
    }];
}


- (void)cancelRequest
{
    [self.operationQueue cancelAllOperations];
    
//    [((UIActivityIndicatorView*)[[[UIApplication sharedApplication].keyWindow viewWithTag:1212] viewWithTag:1100]) stopAnimating];
//    [[UIApplication sharedApplication].keyWindow viewWithTag:1212].hidden = YES;

}
- (void)showAlertView:(NSString*)title subtitle:(NSString*)subtitle
{
    __block URBAlertView *alertView = [URBAlertView dialogWithTitle:title subtitle:subtitle];
	alertView.blurBackground = YES;
    //	[alertView addButtonWithTitle:@"Close"];
	[alertView addButtonWithTitle:@"确定"];
	[alertView setHandlerBlock:^(NSInteger buttonIndex, URBAlertView *alertView) {
		NSLog(@"button tapped: index=%i", buttonIndex);
		[alertView hideWithCompletionBlock:^{
			// stub
		}];
	}];
	[alertView showWithAnimation:URBAlertAnimationFlipHorizontal];
    
}
- (void)isHidenLoadingView:(BOOL)isHiden
{
    if (_isHidenLoadingView) {
        [UIView animateWithDuration:0.3f animations:^{
            //[[UIApplication sharedApplication].keyWindow viewWithTag:1212].hidden = !isHiden;
            if (isHiden) {
                //[((UIActivityIndicatorView*)[[[UIApplication sharedApplication].keyWindow viewWithTag:1212] viewWithTag:1100]) startAnimating];
            }
            else{
                //[((UIActivityIndicatorView*)[[[UIApplication sharedApplication].keyWindow viewWithTag:1212] viewWithTag:1100]) stopAnimating];
            }
            
        }];
    }
    else
    {
        //[((UIActivityIndicatorView*)[[[UIApplication sharedApplication].keyWindow viewWithTag:1212] viewWithTag:1100]) stopAnimating];
        //[[UIApplication sharedApplication].keyWindow viewWithTag:1212].hidden = YES;
    }

    
}
-(void)paramMd5WithSign:(NSMutableDictionary*)dic
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    [dic setObject:app_Version forKey:@"version"];
    [dic setObject:@"1" forKey:@"device_type"];
    [dic setObject:[UIDevice currentDevice].identifierForVendor.UUIDString forKey:@"imei"];
    //zsg:新添加
    NSString * deviceName = [[UIDevice currentDevice] model];
    [dic setObject:deviceName forKey:@"phone_model"];
    NSString * phoneVersion = [[UIDevice currentDevice] systemVersion];
    [dic setObject:phoneVersion forKey:@"os_version"];
    //dip
    [dic setObject:@"640X1136" forKey:@"dpi"];
    
    NSArray* arraykey = [dic allKeys];
    NSMutableString* stringkey = [[NSMutableString alloc] init];
    for(int i = 0 ; i < [arraykey count] ;i++)
    {
        [stringkey appendString:[arraykey objectAtIndex:i]];
    }
    //[stringkey appendString:@"lmslmslms"];
    [dic setObject:[self md5:stringkey] forKey:@"auth_code"];
    NSLog(@"%@",dic);
}

- (NSString *) md5:(NSString*)string
{
    const char *cStr = [string UTF8String];
    unsigned char result[16];
    CC_MD5( cStr, (unsigned int) strlen(cStr), result);
    return [NSString stringWithFormat:
			@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
			result[0], result[1], result[2], result[3],
			result[4], result[5], result[6], result[7],
			result[8], result[9], result[10], result[11],
			result[12], result[13], result[14], result[15]
			];
}



/*************************************************
 Description:POST上传图片方法
 **************************************************/
-(void) postRequestOperation:(NSString *) operationPath
             paramDictionary:(NSMutableDictionary *)paramDic
                onCompletion:(CommonStringResponseBlock) completion
                     onError:(CommonErrorBlock) errorBlock
                  onAnimated:(BOOL)animated imagedata:(NSData*)dataimage imagekey:(NSString*)stringimagekeyname
{
    _isHidenLoadingView = animated;
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [paramDic setObject:@"1" forKey:stringimagekeyname];
    [self paramMd5WithSign:paramDic];
    [paramDic removeObjectForKey:stringimagekeyname];
    
    
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    [self POST:operationPath parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         [formData appendPartWithFileData:dataimage name:stringimagekeyname fileName:@"upimage.png" mimeType:@"image/jpeg"];
     }
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
         NSLog(@"JSON: %@", responseObject);
         NSLog(@"%s",object_getClassName(responseObject));
         if( [responseObject isKindOfClass:[NSDictionary class]])
         {
             if((!responseObject || responseObject == nil) )
             {
                 [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                 return ;
             }
             
         }
         
         completion([responseObject JSONString]);
     }
    failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
         if (error.code) {
             NSLog(@"%@", [error debugDescription]);
             [self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
             return;
         }
         errorBlock(error);
     }];
    
}


-(void) postRequestOperationAsset:(NSString *) operationPath
                  paramDictionary:(NSMutableDictionary *)paramDic
                     onCompletion:(CommonStringResponseBlock) completion
                          onError:(CommonErrorBlock) errorBlock
                       onAnimated:(BOOL)animated
                        imagedata:(NSMutableArray*)assetArry
                         imagekey:(NSString*)stringimagekeyname;
{
    _isHidenLoadingView = animated;
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [paramDic setObject:@"1" forKey:stringimagekeyname];
    [self paramMd5WithSign:paramDic];
    [paramDic removeObjectForKey:stringimagekeyname];
    
    
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    
    [self POST:operationPath parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         //[formData appendPartWithFileData:dataimage name:stringimagekeyname fileName:@"upimage.png" mimeType:@"image/jpeg"];
         //上传Image
         ALAsset * asset = nil;
         NSString * str_name = nil;
         NSString * str_name_png = nil;
         for (int i = 0; i < [assetArry count]; i++) {
             asset = [assetArry objectAtIndex:i];
             
             ALAssetRepresentation * rep = [asset defaultRepresentation];
             unsigned long size = (unsigned long)rep.size;
             Byte *buffer = (Byte*)malloc(size);
             NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:size error:nil];
             NSData * data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
             NSLog(@"org:%d", rep.orientation);
             //添加
             str_name = [NSString stringWithFormat:@"img[%d]", i];
             str_name_png = [NSString stringWithFormat:@"img[%d]", i];
             [formData appendPartWithFileData:data
                                         name:str_name
                                     fileName:str_name_png
                                     mimeType:@"image/png"];
         }
     }
       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"JSON: %@", responseObject);
         NSLog(@"%s",object_getClassName(responseObject));
         if( [responseObject isKindOfClass:[NSDictionary class]])
         {
             if((!responseObject || responseObject == nil) )
             {
                 [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                 return ;
             }
             
         }
         
         completion([responseObject JSONString]);
     }
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
         if (error.code) {
             NSLog(@"%@", [error debugDescription]);
             [self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
             return;
         }
         errorBlock(error);
     }];
}

-(void) postRequestOperationAsset1:(NSString *) operationPath
                   paramDictionary:(NSMutableDictionary *)paramDic
                      onCompletion:(CommonStringResponseBlock) completion
                           onError:(CommonErrorBlock) errorBlock
                        onAnimated:(BOOL)animated
                         imagedata:(id)asset
                          imagekey:(NSString*)stringimagekeyname;
{
    _isHidenLoadingView = animated;
    //[AFNetworkActivityIndicatorManager sharedManager].delegate = self;
    
    if (!paramDic) {
        paramDic = [[NSMutableDictionary alloc] init];
    }
    [paramDic setObject:@"1" forKey:stringimagekeyname];
    [self paramMd5WithSign:paramDic];
    [paramDic removeObjectForKey:stringimagekeyname];
    
    
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    self.responseSerializer = [AFJSONResponseSerializer serializer];
    
    [self POST:operationPath parameters:paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         //上传Image
         ALAsset * asset = nil;
         NSString * str_name = nil;
         NSString * str_name_png = nil;

         ALAssetRepresentation * rep = [asset defaultRepresentation];
         unsigned long size = (unsigned long)rep.size;
         Byte *buffer = (Byte*)malloc(size);
         NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:size error:nil];
         NSData * data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
         NSLog(@"org:%d", rep.orientation);
         //添加
         str_name = [NSString stringWithFormat:@"photo"];
         str_name_png = [NSString stringWithFormat:@"photo"];
         [formData appendPartWithFileData:data
                                     name:str_name
                                 fileName:str_name_png
                                 mimeType:@"image/png"];
     }
       success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"JSON: %@", responseObject);
         NSLog(@"%s",object_getClassName(responseObject));
         if( [responseObject isKindOfClass:[NSDictionary class]])
         {
             if((!responseObject || responseObject == nil) )
             {
                 [self showAlertView:@"温馨提示" subtitle:@"网络通讯失败！"];
                 return ;
             }
             
         }
         
         completion([responseObject JSONString]);
     }
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         NSLog(@"Error: %@", error);
         if (error.code) {
             NSLog(@"%@", [error debugDescription]);
             [self showAlertView:@"温馨提示" subtitle:error.localizedDescription];
             return;
         }
         errorBlock(error);
     }];
}

@end












